/* global $,Lang */
let Vue = require('vue');
let _ = require('lodash');

Vue.use(require('vue-resource'));
Vue.directive('chosen', {
    bind: function () {
        // for ajax
        if (this.vm.isAjax) {
            // load data from ajax and refresh
            // !!this.vm.ajaxAPI ? '' : console.warn('chosen ajaxAPI not defined');
            this.vm.$http.get(this.vm.ajaxAPI, null, {
                params: {
                    '_token': $('[name=_token]').val()
                }
            }).then(function (response) {
                var data = response.data;
                _.map(data, function (user) {
                    console.log(user.ID + ':' + user.name);
                });
            });
            return;
        }
        $(this.el).chosen({
            width: '100%',
            placeholder_text_single: this.vm.config.placeHolder || Lang.get('common.please_select_option')
        }).val(this.vm.value).attr('disabled', this.vm.disabled || false).trigger('chosen:updated').change(function (ev) {
            // two-way set
            // this.set(this.el.value);
            var i, len, option, ref;
            var values = [];
            ref = this.el.selectedOptions;
            for (i = 0, len = ref.length; i < len; i++) {
                option = ref[i];
                values.push(option.value);
            }
            // this.set(values);
            this.set(this.el.value);
        }.bind(this));
    },
    update: function (nv, ov) {
        // note that we have to notify chosen about update
        $(this.el).trigger('chosen:updated');
    }
});
